<?php


namespace App\Http\Controllers;


use App\Model\Category;
use App\Model\Goods;

class IndexController extends Controller
{

    public function index()
    {

        // 首页推荐商品
        $rec = Goods::findGoods()->limit(7)->get();

        $goods = collect();
        $top = collect();
        $goods_ids = [];
        foreach ($rec as $key => $good) {
            array_push($goods_ids, $good->id);
            if ($key <= 1) {
                $top->push($good);
            } else {
                $goods->push($good);
            }
        }

        // 获取首页推荐商品分类
        $categories = Category::whereNotNull('thumb')
            ->orderBy('sort', 'desc')->limit(3)->get();

        $cat_ids = [];
        foreach ($categories as $category) {
            array_push($cat_ids, $category->id);
        }

        $goods_two = Goods::findGoods()
            ->whereNotIn('category_id', $cat_ids)
//            ->whereNotIn('id', $goods_ids)
            ->limit(5)->get();

        $cats = Category::whereNotNull('thumb')
            ->whereNotIn('id', $cat_ids)
            ->orderBy('sort', 'desc')
            ->limit(2)->get();


        $template = 'home.index';

        return view($template, [
            'goods' => $goods,
            'category_one' => $categories->first(),
            'category_two' => isset($categories[1]) ? $categories[1] : [],
            'category_three' => isset($categories[2]) ? $categories[2] : [],
            'goods_two' => $goods_two,
            'cats' => $cats,
            'top' => $top
        ]);
    }

}
